import { useState, useCallback, useRef, useEffect } from 'react'
import {
  getBannerList,
  getArchiveList,
  getRecentList,
  getCVList,
  getCVTree,
  getAnimeList,
  getXinFanList,
  getUserInfoFromCache,
} from '../request'
import { Image, Modal, message } from 'antd'
import defaultImage from '@/assets/defaultImage.png'
import { throttle } from '@/utils'

export const useGetBannerList = (date) => {
  const [banner, setBannner] = useState([])
  const [loading, setLoading] = useState(false)

  const updateBannerList = useCallback(async () => {
    try {
      setLoading(true)
      let response = await getBannerList(date)
      setBannner(response)
      setLoading(false)
      return response
    } catch (error) {}
  }, [])
  return {
    banner,
    setBannner,
    updateBannerList,
    loading,
  }
}

export const useGetArchiveList = () => {
  const [archive, setArchive] = useState([])

  const updateArchiveList = useCallback(async () => {
    try {
      let response = await getArchiveList()
      response = response.map((item) => {
        return {
          key: item.id.toString(),
          label: item.name,
        }
      })
      setArchive(response)
      return response
    } catch (error) {}
  }, [])

  return {
    archive,
    setArchive,
    updateArchiveList,
  }
}

export const useGetRecentList = () => {
  const [recent, setRecent] = useState([])
  const [loading, setLoading] = useState(false)

  const updateRecentList = useCallback(async () => {
    try {
      setLoading(true)
      let response = await getRecentList()
      response = response.map((item) => {
        return {
          key: item.id,
          poster: (
            <Image
              width={100}
              src={item.poster}
              loading="lazy"
              fallback={defaultImage}
            />
          ),
          title: item.title,
          episodes: item.mapVOList ? item.mapVOList.length : 1,
          enclosure: item.enclosure,
          pubDate: item.pubDate,
          mapVOList: item.mapVOList,
          magnetChain: item.magnetChain,
        }
      })
      setRecent(response)
      setLoading(false)
      return response
    } catch (error) {}
  }, [])

  return {
    recent,
    setRecent,
    updateRecentList,
    loading,
  }
}

export const useGetCVList = () => {
  const [cvlist, setCVList] = useState([])
  const [loading, setLoading] = useState(false)
  const [cvtree, setCvTree] = useState([])

  let updateCVList = useCallback(async (code) => {
    let orderId
    try {
      setLoading(true)
      let response = await getCVList()

      if (code) {
        orderId = code
      } else {
        orderId = response[0].code
      }
      let cvtreeResponse = await getCVTree(orderId)
      setCVList(response)
      setCvTree(cvtreeResponse)
      setLoading(false)
      return response
    } catch (error) {}
  }, [])

  return {
    cvlist,
    cvtree,
    setCVList,
    setCvTree,
    updateCVList,
    loading,
  }
}

export const useGetCVTree = () => {
  const [cvtree, setTree] = useState([])
  const [loading, setLoading] = useState(false)

  const updateGetCVTree = useCallback(async () => {
    try {
      setLoading(true)
      let data = await getCVTree()
      let info = preProcessInfo(data)
      setTree(info)
      setLoading(false)
      return info
    } catch (error) {}
  }, [])

  const preProcessInfo = (info) => {
    let newNodes = []
    for (let n of info.data.nodes) {
      n.id = parseInt(String(n.id))
      newNodes.push(n)
    }
    info.data.nodes = newNodes
    return info
  }

  return {
    cvtree,
    setTree,
    updateGetCVTree,
    loading,
  }
}

export const useGetAnimeList = () => {
  const [anime, setAnime] = useState([])
  const [loading, setLoading] = useState(false)

  const updateAnimeList = useCallback(async (w) => {
    try {
      setLoading(true)
      const { uId, token, loginType } = getUserInfoFromCache() ?? {}
      const response = await getAnimeList(w, uId, token, loginType)
      setAnime(response)
      setLoading(false)
      return response
    } catch (error) {}
  }, [])

  return {
    anime,
    setAnime,
    updateAnimeList,
    loading,
  }
}

export const useGetXinFanList = () => {
  const [xinfan, setXinFan] = useState([])
  const [loading, setLoading] = useState(false)
  const [internalPlayer, setInternalPlayer] = useState(true)

  const updateXinFanList = useCallback(async (id, ep) => {
    try {
      setLoading(true)
      const { uId, token, loginType } = getUserInfoFromCache() ?? {}
      let response = await getXinFanList(id, ep, uId, token, loginType)
      setXinFan(response)
      setLoading(false)
      return response
    } catch (error) {}
  }, [])

  return {
    xinfan,
    internalPlayer,
    setInternalPlayer,
    setXinFan,
    updateXinFanList,
    loading,
  }
}

export const useShowPromiseModal = (type = 'info') => {
  const target = Modal[type]

  const ShowPromiseModal = (config) => {
    target({
      title: '标题',
      icon: '图标',
      content: '内容',
      okText: '确认',
      cancelText: '取消',
      ...config,
    })
  }

  return ShowPromiseModal
}

export const useOpenMessageThrottle = (delay = 1000, defaultConfig) => {
  const throttleFn = throttle((config) => {
    message.open({ ...defaultConfig, ...config })
  }, delay)

  const openMessage = useCallback(throttleFn, [throttleFn])
  return openMessage
}

const getWindowDimensions = () => {
  const { innerWidth: width, innerHeight: height } = window
  return {
    width,
    height,
  }
}

export const useWindowDimensions = () => {
  const [windowDimensions, setWindowDimensions] = useState(
    getWindowDimensions()
  )

  useEffect(() => {
    function handleResize() {
      setWindowDimensions(getWindowDimensions())
    }

    window.addEventListener('resize', handleResize)
    return () => window.removeEventListener('resize', handleResize)
  }, [])

  return windowDimensions
}
